﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using AmkeniCrossLoginApplication.Data_Access;

namespace Amkeni_System.Project
{
    public partial class Add_Report : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, EventArgs e)
        {
            /*if (User.IsInRole("IP"))
            {
                MasterPageFile = "~/MasterPages/Project.Master";
            }
            if (User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/Programme.Master";
            }
            if (User.IsInRole("Administrator"))
            {
                MasterPageFile = "~/MasterPages/CO.Master";
            }
            if (User.IsInRole("IP") && User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/ProgProject.Master";
            }*/
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void ReportButton_Click(object sender, EventArgs e)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    int projID = int.Parse(IPList.SelectedValue.Trim());
                    int reportPeriodID = int.Parse(ReportPeriodList.SelectedValue.Trim());
                    int yearID = int.Parse(YearList.SelectedValue.Trim());
                    int rfpID = int.Parse(RFPList.SelectedValue.Trim());

                    var myReport = (from report in db.ip_report
                                    where report.ip_id == projID &&
                                    report.year_id == yearID &&
                                    report.report_period_id == reportPeriodID &&
                                    report.RFP_id == rfpID
                                    select report).FirstOrDefault();

                    if (myReport == null)
                    {
                        if (!User.IsInRole("Administrator"))
                        {
                            var UProject = (from u in db.users where u.email == User.Identity.Name select u.ip_id).Single();
                            if (UProject == null)
                            {
                                Error.Text = "You cannot create this report";
                                Error.Visible = true;
                                Error.ForeColor = System.Drawing.Color.Red;
                                return;
                            }

                            //string[] theProj = UProject.Split(new Char[] { ',' });

                            //foreach (var UProjAccess in theProj)
                            //{
                            try
                            {
                                // projToAccess = long.Parse(UProject);

                                if (UProject == projID)
                                {
                                    //=================================+
                                    //  Add a new IP_Report Record     |
                                    //=================================+
                                    ip_report pr = new ip_report();
                                    pr.ip_id = projID;
                                    pr.year_id = yearID;
                                    pr.report_period_id = reportPeriodID;
                                    pr.RFP_id = rfpID;
                                    pr.report_status_id = 1;
                                    pr.project_editor = EditorTextBox.Text;
                                    pr.saved = true;
                                    pr.saved_date = DateTime.Now;
                                    db.ip_report.Add(pr);

                                    var beneficiaries = from data in db.beneficiaries
                                                        where data.active == true
                                                        select data.beneficiary_id;
                                    foreach (var pple in beneficiaries)
                                    {
                                        //======================================+
                                        //  Add a direct beneficiary report     |
                                        //======================================+
                                        ip_direct_beneficiary group = new ip_direct_beneficiary();
                                        group.ip_id = projID;
                                        group.year_id = yearID;
                                        group.report_period_id = reportPeriodID;
                                        group.RFP_id = rfpID;
                                        group.beneficiary_id = pple;
                                        group.male = 0;
                                        group.female = 0;
                                        db.ip_direct_beneficiary.Add(group);
                                    }
                                    //======================================+
                                    //  Add the IP Reporting indicators     |
                                    //======================================+
                                    /*var _ipPlan = db.monitoring_data_collection_frequency_connector
                                            .Where(data => data.report_period_id == reportPeriodID
                                            && data.monitoring_plan.ip_id == projID
                                            && data.monitoring_plan.year_id == yearID
                                            && data.monitoring_plan.RFP_id == rfpID)
                                            .Select(x => x.monitoring_plan.activity_indicator_connector).Distinct();*/

                                    var _ipPlan = db.monitoring_data_collection_frequency_connector
                                        .Where(data => data.report_period_id == reportPeriodID
                                        && data.monitoring_plan.ip_id == projID
                                        && data.monitoring_plan.year_id == yearID
                                        && data.monitoring_plan.RFP_id == rfpID)
                                        .Join(db.monitoring_plan,
                                        c => c.monitoring_plan_id,
                                        cm => cm.monitoring_plan_id,
                                        (c, cm) => new { monitoring_data_collection_frequency_connector = c, monitoring_plan = cm })
                                        .Join(db.activity_indicator_connector,
                                        d => d.monitoring_plan.monitoring_plan_id,
                                        dm => dm.monitoring_plan_id,
                                        (d, dm) => new { monitoring_plan = d, activity_indicator_connector = dm })
                                        .Select(x => x.activity_indicator_connector.indicator_id).Distinct();

                                    foreach (var ipPlan in _ipPlan)
                                    {
                                        indicator_result indReport = new indicator_result();
                                        indReport.ip_id = projID;
                                        indReport.year_id = yearID;
                                        indReport.report_period_id = reportPeriodID;
                                        indReport.RFP_id = rfpID;
                                        indReport.indicator_id = ipPlan;
                                        indReport.status_id = 1;//Change the status to draft by default
                                        db.indicator_result.Add(indReport);
                                    }
                                    db.SaveChanges();
                                    ScriptManager.RegisterStartupScript(this, this.GetType(), 
                                        "alert",
                                        "alert('Report Created');window.location ='Amkeni_System/Project/Saved_Projects/';",
                                        true);
                                }
                                else
                                {
                                    Error.Text = "You cannot create this report";
                                    Error.Visible = true;
                                    Error.ForeColor = System.Drawing.Color.Red;
                                    return;
                                }
                            }
                            catch
                            {
                                Error.Text = "You cannot create this report";
                                Error.Visible = true;
                                Error.ForeColor = System.Drawing.Color.Red;
                                return;
                            }
                            //}
                        }
                        else
                        {
                            //=================================+
                            //  Add a new IP_Report Record     |
                            //=================================+
                            ip_report pr = new ip_report();
                            pr.ip_id = projID;
                            pr.year_id = yearID;
                            pr.report_period_id = reportPeriodID;
                            pr.RFP_id = rfpID;
                            pr.report_status_id = 1;
                            pr.project_editor = EditorTextBox.Text.Trim();
                            pr.saved = true;
                            pr.saved_date = DateTime.Now;
                            db.ip_report.Add(pr);

                            var beneficiaries = from data in db.beneficiaries select data.beneficiary_id;
                            foreach (var pple in beneficiaries)
                            {
                                //======================================+
                                //  Add a direct beneficiary report     |
                                //======================================+
                                ip_direct_beneficiary group = new ip_direct_beneficiary();
                                group.ip_id = projID;
                                group.year_id = yearID;
                                group.report_period_id = reportPeriodID;
                                group.RFP_id = rfpID;
                                group.beneficiary_id = pple;
                                group.male = 0;
                                group.female = 0;
                                db.ip_direct_beneficiary.Add(group);
                            }
                            //======================================+
                            //  Add the IP Reporting indicators     |
                            //======================================+

                            var addIpPlanIndicators = db.monitoring_data_collection_frequency_connector
                                .Where(data => data.report_period_id == reportPeriodID
                                && data.monitoring_plan.ip_id == projID
                                && data.monitoring_plan.year_id == yearID
                                && data.monitoring_plan.RFP_id == rfpID)
                                .Join(db.monitoring_plan,
                                c => c.monitoring_plan_id,
                                cm => cm.monitoring_plan_id,
                                (c, cm) => new { monitoring_data_collection_frequency_connector = c, monitoring_plan = cm })
                                .Join(db.activity_indicator_connector,
                                d => d.monitoring_plan.monitoring_plan_id,
                                dm => dm.monitoring_plan_id,
                                (d, dm) => new { monitoring_plan = d, activity_indicator_connector = dm })
                                .Select(x => x.activity_indicator_connector.indicator_id).Distinct();

                            foreach (var _addIpPlanIndicators in addIpPlanIndicators)
                            {
                                indicator_result indReport = new indicator_result();
                                indReport.ip_id = projID;
                                indReport.year_id = yearID;
                                indReport.report_period_id = reportPeriodID;
                                indReport.RFP_id = rfpID;
                                indReport.indicator_id = _addIpPlanIndicators;
                                indReport.status_id = 1;//Change the status to draft by default
                                db.indicator_result.Add(indReport);
                            }

                            /*var _ipPlan = db.monitoring_data_collection_frequency_connector
                                .Where(data => data.report_period_id == reportPeriodID
                                    && data.monitoring_plan.ip_id == projID
                                    && data.monitoring_plan.year_id == yearID)
                                    .Select(data => data.monitoring_plan.monitoring_plan_id);
                            
                            foreach (var ipPlan in _ipPlan)
                            {
                                var _ipPlanIndicators = db.activity_indicator_connector
                                    .Where(data => data.monitoring_plan_id == ipPlan)
                                    .Select(data => data.indicator_id);

                                foreach (var ipPlanIndicators in _ipPlanIndicators.Distinct())
                                {
                                    indicator_result indReport = new indicator_result();
                                    indReport.ip_id = projID;
                                    indReport.year_id = yearID;
                                    indReport.report_period_id = reportPeriodID;
                                    indReport.indicator_id = ipPlanIndicators;
                                    db.indicator_result.Add(indReport);
                                }
                            }*/
                            db.SaveChanges();
                            ScriptManager.RegisterStartupScript(this, this.GetType(),
                                        "alert",
                                        "alert('Report Created');window.location ='Amkeni_System/Project/Saved_Projects/';",
                                        true);
                        }
                    }
                    else
                    {
                        Error.Text = "That report has already been added to the database," +
                                " Please check again";
                        Error.Visible = true;
                        Error.ForeColor = System.Drawing.Color.Red;
                        //Response.Redirect("~/Amkeni_System/Project/Saved_Projects/", true);
                    }
                }
                catch (Exception ex)
                {
                    Error.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    Error.Visible = true;
                }
                finally
                {
                    db.SaveChanges();
                }
            }
        }

        protected void RFPList_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities())
            {
                try
                {
                    int Rfp_id = int.Parse(RFPList.SelectedValue.Trim());

                    var selectedIPs = from data in db.implementing_partner_metadata
                                      where data.RFP_id == Rfp_id
                                      select new
                                      {
                                          data.implementing_partner.ip_id,
                                          data.implementing_partner.abbreviation
                                      };

                    IPList.DataSource = selectedIPs.ToList();
                    IPList.DataBind();
                }
                catch (Exception ex)
                {
                    Error.Text = "Database error on Selection of Implementing Partners Drop Down List : " + ex.Message + " : " + ex.StackTrace;
                    Error.Visible = true;
                }
            }
        }
    }
}